package edu.itla.medifacil.persistence.managers;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.Test;

public class TestManager {
	private EntityManager em = null;
	
	public TestManager() {
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	
	public Test save( Map<String, String> parameters ){
		Test test = new Test();
		String description = parameters.get("description");
		
		if( parameters.get("id") != null && parameters.get("id").trim().length() > 0 )
			test = this.find( Integer.parseInt(parameters.get("id")) );
		
		test.setDescription(description);
		
		em.getTransaction().begin();
		em.persist( test );
		em.getTransaction().commit();
		
		return test;
	}
	
	public void delete( int testId ){
		em.getTransaction().begin();
		em.createQuery("DELETE FROM TestResult t WHERE t.test.id="+testId).executeUpdate();
		em.createQuery("DELETE FROM Test WHERE id="+testId).executeUpdate();
		em.getTransaction().commit();
	}

	public Test find( int testId ){
		em.clear();
		return em.find( Test.class, testId);
	}
	
	@SuppressWarnings("unchecked")
	public List<Test> findAll(){
		return (List<Test>) em.createQuery( "SELECT t FROM Test t").getResultList();
	}
	

}
